<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class FixUserInfo extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        $database = env('DB_DATABASE');

        DB::statement("ALTER TABLE {$database}.user MODIFY COLUMN nickname VARCHAR(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");

        $nextOpenId = 1;

        while($nextOpenId){

            $nextOpenId = $nextOpenId === 1 ? null : $nextOpenId;

            $userService = app('wechat')->user;

            $users = $userService->lists($nextOpenId);

            if($users->data){
                foreach ($users->data['openid'] as $openId) {
                    $info = $userService->get($openId);

                    \App\Model\User::withTrashed()->updateOrCreate(['open_id' => $info->openid], [
                        'subscribed_at' => \Carbon\Carbon::createFromTimestamp($info->subscribe_time)->toDateTimeString(),
                        'nickname' => $info->nickname,
                        'avatar' => $info->headimgurl
                    ]);
                }
            }

            if($users->next_openid){
                $nextOpenId = $users->next_openid;
            }else{
                break;
            }

        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $database = env('DB_DATABASE');
        DB::statement("ALTER TABLE {$database}.user MODIFY COLUMN nickname VARCHAR(64) CHARACTER SET utf8 COLLATE utf8_general_ci;");
    }
}
